package org.jawa.exam.paper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jawa.core.cache.Cache;
import org.jawa.core.cache.CacheFactory;
import org.jawa.core.database.DbConnectionManager;
import org.jawa.exam.model.QuestionOption;
import org.jawa.exam.model.QuestionSort;
import org.jawa.jdbc.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QuestionSortManager {

	private static final Logger Log = LoggerFactory.getLogger(QuestionSortManager.class);

	/**
	 * 根据试题类型查询的SQL.
	 */
	private static final String QUESTION_COUNT = "SELECT count(*) FROM QUESTION WHERE question_type=?";

	// 试题分类缓存
	private Cache<Long, QuestionSort> questionSortCache;

	// 单一实例.
	private static class QuestionSortManagerContainer {
		private static QuestionSortManager instance = new QuestionSortManager();
	}

	public static QuestionSortManager getInstance() {
		return QuestionSortManagerContainer.instance;
	}

	private QuestionSortManager() {
		questionSortCache = CacheFactory.createCache("questionSort");
	}
	
	/**
	 * 创建试题分类
	 * @param questionSort 
	 * @return
	 * @throws Exception
	 */
	public QuestionSort createQuestionSort(QuestionSort questionSort) throws Exception{
		Connection con = null;
		boolean abortTransaction = false;
		try {
			con = DbConnectionManager.getTransactionConnection();
			JdbcUtils.insertTableFromBean(con, "QUESTIONSORT", questionSort, "CachedSize");
		} catch (Exception e) {
			abortTransaction = true;
			Log.error("将试题分类存入数据库时发生错误!", e);
			throw e;
		} finally {
			DbConnectionManager.closeTransactionConnection(con, abortTransaction);
		}
		questionSortCache.put(questionSort.getSortId(), questionSort);
		return questionSort;
	}
	
	/**
	 * 返回所有的试题分类
	 * 
	 * @Title: QuestionManager
	 * @Description: TODO
	 * @param @return
	 * @throws
	 */
	public List<QuestionSort> getQuestionSorts() {
		List<QuestionSort> sorts = new ArrayList<QuestionSort>();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT * FROM QUESTIONSORT WHERE 1=1 ");
		try {
			sorts = JdbcUtils.queryToBeanList(QuestionSort.class, sql.toString());
		} catch (SQLException e) {
			Log.error("查询试题分类信息时发生错误!", e);
		}

		return sorts;
	}
}
